package com.celan.year2023.month01.day01;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

public class Solution {
    //输入：nums = [5,7,8,8,10], target = 8
    //输出：[3,4]
    public int[] searchRange(int[] nums, int target) {
        int start = -1, end = -1;
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] == target) {
                int l = mid;
                while (l > 0 && nums[l - 1] == target) l--;
                start = l;
                int r = mid;
                while (r < nums.length - 1 && nums[r + 1] == target) r++;
                end = r;
                break;
            }
            if (nums[mid] > target) right = mid - 1;
            if (nums[mid] < target) left = mid + 1;
        }
        return new int[]{start, end};
    }

    //输入：candidates = [2,3,6,7], target = 7
    //输出：[[2,2,3],[7]]

    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    int[] candidates;
    int target;

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        this.candidates = candidates;
        this.target = target;
        Arrays.sort(candidates);
        backTrack(0, 0);
        return res;
    }

    private void backTrack(int idx, int sum) {
        if (sum == target) res.add(new ArrayList<>(path));
        if (sum > target) return;

        for (int i = idx; i < candidates.length; i++) {
            if (candidates[i] > target) break;
            path.add(candidates[i]);
            backTrack(i, sum + candidates[i]);
            path.remove(path.size() - 1);
        }
    }

    public int countDigits(int num) {
        int count = 0;
        String s = String.valueOf(num);
        for (int i = 0; i < s.length(); i++) {
            int n = s.charAt(i) - '0';
            if (num % n == 0) count++;
        }
        return count;
    }

    public char repeatedCharacter(String s) {
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if(s.substring(0,i).contains(String.valueOf(c))){
                return c;
            }
        }
        return 0;
    }
}
